//
//  ILMusicDetailViewController.m
//  ILife
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILMusicDetailViewController.h"
#import "ILMusicDetailView.h"
#import "ILRecommendTableViewCell.h"
#import "ILMusicPlayModel.h"
#import "ILMusicPlayerManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "FMDatabase.h"

@interface ILMusicDetailViewController ()<UITableViewDataSource, UITableViewDelegate,RSliderViewDelegate>
{
    NSInteger buttonCount;
}
@property(nonatomic, strong)NSTimer *timer;
@property(nonatomic, strong)ILMusicDetailView *musicDetailView;
@property(nonatomic, strong)NSMutableArray *recommendArray;
@property(nonatomic, strong)ILMusicPlayModel *playModel;

@property(nonatomic, strong)NSMutableArray *isnewURlArray;
@property(nonatomic, strong)FMDatabase *dataBase;
@end

@implementation ILMusicDetailViewController

-(NSMutableArray *)isnewURlArray
{
    if (_isnewURlArray == nil) {
        self.isnewURlArray = [NSMutableArray array];
    }
    return _isnewURlArray;
}

-(NSMutableArray *)recommendArray
{
    if (_recommendArray == nil) {
        self.recommendArray = [NSMutableArray array];
    }
    return _recommendArray;
}

// 请求列表数据
-(void)requestData
{
    NSString *htmlStr = [NSString stringWithFormat:@"http://wawa.fm/CmsSite/a/cms/article/myrandom?number=4&categoryId=543&kuayu=true&did=%@",_musicID];
    NSURL *url = [NSURL URLWithString:htmlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
    
    [NSURLConnection sendAsynchronousRequest:request queue:( [NSOperationQueue currentQueue]) completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
  
        if (data != nil) {
            NSData *newData = [self changeData:data];
            
            NSArray *arr = [NSJSONSerialization JSONObjectWithData:newData options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
            NSArray *realArray = arr[0];
            
            for (NSDictionary *dic in realArray) {
                ILMusicListModel *recommendModel = [[ILMusicListModel alloc]init];
                [recommendModel setValuesForKeysWithDictionary:dic];
                [self.recommendArray addObject:recommendModel];
            }
            [_musicDetailView.recommendTableView reloadData];
        }else
        {
        
            NSLog(@"请求失败：%@",connectionError);
        
        }
        

    }];
}

-(NSData *)changeData:(NSData *)data
{
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *newString =[str stringByReplacingOccurrencesOfString:@"(" withString:@"["];
    NSString *lastString = [newString stringByReplacingOccurrencesOfString:@")" withString:@"]"];
    NSString *string = [lastString stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@""];
    NSLog(@"lastString = %@",string);
    NSData *realData = [string dataUsingEncoding:NSUTF8StringEncoding];
    return realData;
}
// 请求音乐连接进行播放
-(void)requestMusicData
{
    NSString *htmlStr = [NSString stringWithFormat:@"http://wawa.fm/CmsSite/a/cms/article/findByIdlls?type=y&ids=%@",_musicID];
    
    NSURL *url = [NSURL URLWithString:htmlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
    [NSURLConnection sendAsynchronousRequest:request queue:( [NSOperationQueue currentQueue]) completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        if (data != nil) {
            NSData *realData = [self changeData:data];
            NSArray *realArr = [NSJSONSerialization JSONObjectWithData:realData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            NSLog(@"realArr =  %@",realArr[0]);
            NSDictionary *dic = realArr[0][0];
            NSLog(@"dic = %@",dic);
            
            [_playModel setValuesForKeysWithDictionary:dic];
            _musicDetailView.musicPlayModel = _playModel;
            
            //    有网络请求出其他数据时候，再去用上个页面传过来的值进行赋值
//            _musicDetailView.detailListModel = _musicListModel;
//            _musicDetailView.detailListModel = _playModel;
            
            
            
            
           // NSLog(@"-------------%@",_musicListModel.articleData.songname);
        }else
        {
        
            NSLog(@"请求失败：%@",connectionError);
        }
       
    }];
}

-(void)addTofavorite
{


    UIAlertController *alertCollect =[UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertController *alertCollected =[UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        BOOL isCollect = [self isCollect];
        if (isCollect == NO) {
            [_dataBase executeUpdate:@"insert into ILFavoriteMusic(musicId ,image, songname,title) values (?,?,?,?)",_musicID,_playModel.image,_playModel.articleData.songname,_playModel.title];
            [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"collected"]];
            [_dataBase close];
            [self presentViewController:alertCollect animated:YES completion:nil];
            
        }else
        {
             [self presentViewController:alertCollected animated:YES completion:nil];
        }
       [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(collected) userInfo:nil repeats:NO];
}


-(void)collected
{
    [self dismissViewControllerAnimated:YES completion:nil];
}




-(BOOL)isCollect
{
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"ILive.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"filePath = %@",filePath);
    if ([_dataBase open]) {
        NSLog(@"数据库dddd打开成功");
        //[_dataBase executeUpdate:@"drop table ILFavoriteMusic"];
        [_dataBase executeUpdate:@"create table ILFavoriteMusic(musicId text, image text, songname text,title text)"];
    }else
    {
        NSLog(@"数据库ddddd打开失败");
    }
    FMResultSet *resultSet =[_dataBase executeQueryWithFormat:@"select *from ILFavoriteMusic"];
    while ([resultSet next]) {
        NSString *musicId = [resultSet stringForColumn:@"musicId"];
        if ([_musicID isEqualToString:musicId]) {
            //  判断是否收藏了
            return YES;
        }
    }
    return NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    buttonCount = 1;
    _playModel = [[ILMusicPlayModel alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
//   [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
//    [self.navigationItem.backBarButtonItem setTintColor:[UIColor blackColor]];
    self.navigationItem.title = @"乐人";
    
    
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"collect"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(addTofavorite)];
    BOOL isCollect = [self isCollect];
    if (isCollect == YES) {
        [shareItem setImage:[UIImage imageNamed:@"collected"]];
    }
    self.navigationItem.rightBarButtonItem = shareItem;
    
    
    _musicDetailView = [[ILMusicDetailView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _musicDetailView.recommendTableView.delegate = self;
    _musicDetailView.recommendTableView.dataSource =self;
    [_musicDetailView.recommendTableView registerClass:[ILRecommendTableViewCell class] forCellReuseIdentifier:@"ILRecommendTableViewCell"];
    [_musicDetailView.playButton addTarget:self action:@selector(playMusic) forControlEvents:(UIControlEventTouchUpInside)];
    _musicDetailView.playView.delegate = self;

    
     [self requestData];
     [self requestMusicData];
     [self.view addSubview:_musicDetailView];
}
-(void)changeSlider
{
    ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
    if (manager.finishTime != 0) {
        [_musicDetailView.playView setValue:((CGFloat)manager.currentTime /(CGFloat)manager.finishTime) withAnimation:YES completion:^(BOOL finished) {
        }];
        
    }
    NSLog(@"float =========%lf",(CGFloat)manager.currentTime /(CGFloat)manager.finishTime);
    NSLog(@"manager.currentTime == %lu",(unsigned long)manager.currentTime);
    
    if (manager.currentTime == manager.finishTime) {
        [_timer invalidate];
        _timer = nil;
        buttonCount = 1;
    }
}



//-(void)isNewURL:(ILMusicPlayModel*)model
//{
//    ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
//    [self.isnewURlArray addObject:model.articleData.songurl];
//    
//    if (self.isnewURlArray.count == 2) {
//        if (![self.isnewURlArray[0] isEqualToString:self.isnewURlArray[1]]&& ![self.isnewURlArray[1] isEqualToString:@""]) {
//            //  音乐播放
//
//        [manager playMusicWithURL:[NSURL URLWithString:self.isnewURlArray[1]]];
//        [self.isnewURlArray removeObjectAtIndex:0];
//    }else
//        {
//            [manager playMusicWithURL:[NSURL URLWithString:self.isnewURlArray[0]]];
//        }
//    }
//}

-(void)playMusic
{
    [_timer invalidate];
    _timer = nil;
    if (buttonCount == 1 && ![_playModel.articleData.songurl isEqualToString: @""]) {
        //  音乐播放
        ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
        [manager playMusicWithURL:[NSURL URLWithString:_playModel.articleData.songurl]];
//   播放音乐的同时在后台锁屏界面显示当前播放的专辑
        [self configNowPlayingInfoCenter];
    }
    ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
    [manager playAndPause];
    
    if (manager.isPlay == YES) {
     _timer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeSlider) userInfo:nil repeats:YES];
        
        CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        rotationAnimation.duration = 8;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = MAXFLOAT;
        [_musicDetailView.playImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
        
    }else if(manager.isPlay == NO)
    {

         [_musicDetailView.playImageView.layer removeAnimationForKey:@"rotationAnimation"];
    }
    buttonCount ++;
}

#pragma RSliderViewDelegate
-(void)sliderValueChanged:(RS_SliderView *)sender{
    
    ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
    float f = sender.value;
    CGFloat newTime = (CGFloat)(f * manager.finishTime);
    [[ILMusicPlayerManager shareManager]jumpToNewTime:newTime];
}

-(void)sliderValueChangeEnded:(RS_SliderView *)sender
{
    ILMusicPlayerManager *manager = [ILMusicPlayerManager shareManager];
    float f = sender.value;
    CGFloat newTime = (CGFloat)(f * manager.finishTime);
    [[ILMusicPlayerManager shareManager]jumpToNewTime:newTime];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_WIDTH/5 +40;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recommendArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ILRecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ILRecommendTableViewCell" forIndexPath:indexPath];
    
    ILMusicListModel *model = self.recommendArray[indexPath.row];
    
    cell.recommendListModel = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ILMusicDetailViewController *detailVC = [[ILMusicDetailViewController alloc]init];
    ILMusicListModel *model = self.recommendArray[indexPath.row];
    detailVC.musicID = model.musicId;
//    detailVC.musicListModel.articleData.songname = _playModel.articleData.songname;
    [self.navigationController pushViewController:detailVC animated:YES];
}


// 设置后台播放的图片和专辑
-(void)configNowPlayingInfoCenter
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (_musicDetailView.musicPlayModel != nil) {
        [dic setObject:_musicDetailView.musicPlayModel.articleData.songname forKey:MPMediaItemPropertyTitle];
        [dic setObject:_musicDetailView.musicPlayModel.articleData.singer forKey:MPMediaItemPropertyArtist];
        UIImage *image = _musicDetailView.musicImageView.image;
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [dic setObject:artwork forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic];
    }
}


//// 待机屏的播放暂停不起作用
-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    //Once the view has loaded then we can register to begin recieving controls and we can become the first responder
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    //End recieving events
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
    
    
    [_timer invalidate];
    _timer = nil;

}

// 加上控制监听

-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
   if(event.type == UIEventTypeRemoteControl)
   {
       switch (event.subtype) {
           case UIEventSubtypeRemoteControlPlay:
               
               [[ILMusicPlayerManager shareManager]musicPlay];
              
               break;
           case UIEventSubtypeRemoteControlPause:
               [[ILMusicPlayerManager shareManager]musicPause];
               
               break;
           default:
               
               break;
       }
   }

}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
